package com.example.playbox

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.playbox.utils.MD5Utils

class LoginActivity : AppCompatActivity() {
    // 声明所有按钮
    private lateinit var login: Button
    private lateinit var tvRegister: TextView
    private lateinit var etUsername: EditText
    private lateinit var etPwd: EditText
    private lateinit var savePwd: CheckBox
    private var userName: String? = null
    private var passWord: String? = null
    private var spPsw: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        init()
    }

    private fun init() {
        // 给所有按钮匹配id
        etUsername = findViewById(R.id.username)
        etPwd = findViewById(R.id.pwd)
        savePwd = findViewById(R.id.save_pwd)
        login = findViewById(R.id.loginBtn)
        tvRegister = findViewById(R.id.register)
        // 获取记住的账号密码
        getUserInfo()
        // 登录方法
        login.setOnClickListener {
            getEditString()
            // 对当前用户输入的密码进行MD5加密再进行比对判断。
            val md5Psw = MD5Utils.md5(passWord ?: "")
            // 定义方法 readPsw为了读取用户名，得到密码
            spPsw = readPsw(userName)
            when {
                TextUtils.isEmpty(userName) -> {
                    Toast.makeText(this@LoginActivity, "请输入用户名", Toast.LENGTH_SHORT).show()
                }
                TextUtils.isEmpty(passWord) -> {
                    Toast.makeText(this@LoginActivity, "请输入密码", Toast.LENGTH_SHORT).show()
                }
                md5Psw == spPsw -> {
                    // 一致登录成功
                    Toast.makeText(this@LoginActivity, "welcome！$userName", Toast.LENGTH_SHORT).show()
                    // 保存登录状态，在界面保存登录的用户名和密码
                    saveLoginInfo(userName, passWord)
                    saveLoginStatus(true, userName)
                    // 登录成功后关闭此页面进入主页
                    val data = Intent()
                    data.putExtra("isLogin", true)
                    setResult(RESULT_OK, data)
                    // 关闭登录界面
                    finish()
                    // 跳转到下一个界面
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                }
                spPsw != null && !TextUtils.isEmpty(spPsw) && md5Psw != spPsw -> {
                    Toast.makeText(this@LoginActivity, "密码错误", Toast.LENGTH_SHORT).show()
                }
                else -> {
                    Toast.makeText(this@LoginActivity, "此用户名不存在", Toast.LENGTH_SHORT).show()
                }
            }
        }
        tvRegister.setOnClickListener {
            // 跳转到注册界面
            val intent = Intent(this@LoginActivity, com.example.playbox.RegisterActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    // 获取用户名和密码
    private fun getEditString() {
        userName = etUsername.text.toString().trim()
        passWord = etPwd.text.toString().trim()
    }

    // 保存登录信息
    private fun saveLoginInfo(userName: String?, passWord: String?) {
        // 获取SharedPreferences对象
        val checkBoxLogin = savePwd.isChecked
        val sp = getSharedPreferences("userInfo", MODE_PRIVATE)
        val editor = sp.edit()
        // 设置参数
        if (checkBoxLogin) {
            editor.putString("username", userName)
            editor.putString("password", passWord)
            editor.putBoolean("checkboxBoolean", true)
        } else {
            editor.putString("username", null)
            editor.putString("password", null)
            editor.putBoolean("checkboxBoolean", false)
        }
        editor.apply()
    }

    // 从已经存入的对象中读取密码
    private fun readPsw(userName: String?): String? {
        val sp = getSharedPreferences("loginInfo", MODE_PRIVATE)
        return sp.getString(userName, "")
    }

    // 保存登录状态
    private fun saveLoginStatus(status: Boolean, userName: String?) {
        val sp = getSharedPreferences("loginInfo", MODE_PRIVATE)
        val editor = sp.edit()
        editor.putBoolean("isLogin", status)
        editor.putString("loginUserName", userName)
        editor.apply()
    }

    // 返回注册成功数据
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            val userName = it.getStringExtra("userName")
            if (!TextUtils.isEmpty(userName)) {
                etUsername.setText(userName)
                etUsername.setSelection(userName!!.length)
            }
        }
    }

    // 获得用户已注册的信息
    private fun getUserInfo() {
        val sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE)
        if (sp.getBoolean("checkboxBoolean", false)) {
            etUsername.setText(sp.getString("username", null))
            etPwd.setText(sp.getString("password", null))
            savePwd.isChecked = true
        } else {
            etUsername.setText(sp.getString("username", userName))
            etPwd.setText(sp.getString("password", passWord))
            savePwd.isChecked = false
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }
}